<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">
            {{$t('message.filterCondition')}}
        </div>
           <el-form :model="queryForm" ref="queryForm" label-width="120px" label-position="left" 
            	class="bg-white pd-12px">
            <el-card shadow="never" body-style="padding: 24px;">
            	<el-row :gutter="24" style="height: 70px;">
                  <el-col :span="8">
                     <el-form-item :label="$t('dic.grade') + ':'" prop="grade"
                     :error="(queryForm.projId=='1' && !queryForm.grade && !!queryForm.faculty) ? $t('culture.rules.plsChooseGrade'):''"
                     >
                        <el-date-picker
                          v-model="queryForm.grade"
                          :placeholder="$t('message.plsSelect')"
                          type="year"
                          value-format="yyyy"
                          @change="(queryForm.projId=='1') ? getProfession(queryForm.faculty) : ''"
                          style="width: 100%;"/>
                    </el-form-item>
            	  </el-col>
            <el-col :span="8">
            	   <el-form-item
                  :label="$t('dic.trainingLevel') + ':'"
                   prop=" trainingLevel" >
		               <DictSelect v-model="queryForm.trainingLevel" :data="options.trainingLevel"
                   @change="getProfession(queryForm.faculty)" ></DictSelect>
		             </el-form-item>
          </el-col>
               <el-col :span="8">
            	<el-form-item
               :label="$t('label.college')"
               :placeholder="$t('message.all')"
                prop="faculty">
              <DictSelect v-model="queryForm.faculty" :data="options.faculty"
              @change="getProfession(queryForm.faculty)"></DictSelect>
               </el-form-item>
            	    </el-col>
            	</el-row>
              	<el-row :gutter="24" style="height: 50px;">
                   <el-col :span="8">
                      <el-form-item :label="queryForm.projId==='1'?$t('dic.schoolProfession'):$t('dic.major')">
                        <el-select style="width: 100%;"  v-model="queryForm.profession" :placeholder="$t('message.all')" clearable>
                            <el-option v-for="item in options.profession"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                      </el-form-item>
                  </el-col>
                 
                  <el-col :span="8">
            	        <el-form-item :label="$t('culture.exceptionSetting.exception')">
		                    <el-select style="width: 100%;" v-model="queryForm.type" :placeholder="$t('message.all')">
		                        <el-option v-for="item in options.type"
		                            :key="item.value"
		                            :label="item.label"
		                            :value="item.value">
		                        </el-option>
		                    </el-select>
		                </el-form-item>
            	    </el-col>
            	    <el-col :span="8" >
            	        <el-form-item class="float-right">
            	        	<el-button @click="reset">{{$t('message.reset')}}</el-button>
		                    <el-button type="primary" @click="getProfessions">{{$t('message.filter')}}</el-button>   
		                </el-form-item>
            	    </el-col>
            	</el-row>
        </el-card>
      </el-form> 
        <div class="edu-page-title mg-top">
            {{ $t('culture.exceptionSetting.list') }}
        </div>
        <el-card shadow="never" body-style="padding: 24px;">
          <div class="edu-opertion-bar">
                <div class="float-right">
                    <el-button @click="addExcept" >{{$t('message.add')}}</el-button>
                </div>
            </div>
            <el-table :data="tableData" size="mini" @selection-change="handleSelectionChange" stripe>
                <!-- <el-table-column type="selection" width="30"></el-table-column> -->
                <el-table-column type="index" width="80" label="序号" align="center"></el-table-column>
                <el-table-column :label="$t('culture.profession.proCode')">
                    <template slot-scope="scope">
                      <span :title="scope.row.professionClassName">{{scope.row.profession}}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('culture.profession.proCodeName')">
                    <template slot-scope="scope">
                      <span :title="scope.row.professionClassName">{{scope.row.professionName}}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('label.grade')">
                    <template slot-scope="scope">{{scope.row.grade}}</template>
                </el-table-column>
                <el-table-column :label="$t('label.college')">
                    <template slot-scope="scope">
                      <span :title="scope.row.professionClassName">{{scope.row.facultyI18n}}</span>
                      </template>
                </el-table-column>
                <el-table-column :label="$t('label.trainingLevel')">
                    <template slot-scope="scope">{{scope.row.trainingLevelI18n}}</template>
                </el-table-column>
                <el-table-column :label="$t('culture.exceptionSetting.exception')">
                    <template slot-scope="scope">{{getTypeStr(scope.row.type)}}</template>
                </el-table-column>
                  <el-table-column :label="$t('message.operating')">
                    <template slot-scope="scope">
                        <el-button type="text" @click="editExcept(scope.row)" size="mini">{{$t('message.edit')}}</el-button>
                        <el-button type="text" @click="delExcept(scope.row.id)" size="mini">{{$t('message.delete')}}</el-button>
                      <!--   <el-button type="text" @click="editTemplate" v-if="functions['edit_workflow']" size="mini">{{$t('message.edit')}}</el-button>
                        <el-button type="text" @click="deleteTemplate(scope.row)" v-if="functions['delete_workflow']" size="mini">{{$t('message.delete')}}</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        @size-change="onPageSizeChange"
                        @current-change="onCurrentPageChange"
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryForm.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="queryForm.total_" style="float: right;margin:10px 60px 0 0;">
                    </el-pagination>
                </div>
            </div>
        </el-card>
    <!-- 编辑/新增页面 -->
    <el-dialog
      :title="dialogTitle"
      width="50%"
      :visible.sync="showDialog"
      ref="model"
      @close="resetFormValidate()"
      :close-on-press-escape="false"
      :close-on-click-modal="false">
        <el-form
        :model="model"
        ref="model"
        label-position="left"
        label-width="80px"
        :rules="rules">
    <el-row :gutter="24"   style="height: 50px;">
       <el-col :span="12">
           <el-form-item  :label="$t('dic.grade') + ':'" prop="grade">
              <el-date-picker
                v-model="model.grade"
                :placeholder="$t('message.plsSelect')"
                type="year"
                value-format="yyyy" 
                @change="(queryForm.projId=='1') ? getProfessionEdit(model.faculty) : ''"
                style="width: 100%;"/>
            </el-form-item>
     </el-col>
     <el-col :span="12">
          <el-form-item   :label="$t('dic.trainingLevel') + ':'"  prop="trainingLevel" >
		         <DictSelect v-model="model.trainingLevel" :data="options.trainingLevel" @change="getProfessionEdit(model.faculty)" ></DictSelect>
		       </el-form-item>
     </el-col>
	</el-row>
  <el-row :gutter="24" style="height: 50px;">
     <el-col :span="12">
          <el-form-item
              :label="$t('label.college')"
              :placeholder="$t('message.all')"
              prop="faculty">
             <DictSelect v-model="model.faculty" :data="options.faculty" @change="getProfessionEdit(model.faculty)"></DictSelect>
          </el-form-item>
      </el-col>
      <el-col :span="12"> 
        <el-form-item :label="queryForm.projId==='1'?$t('dic.schoolProfession'):$t('dic.major')"  prop="profession">
            <el-select style="width: 100%;"  v-model="model.profession" :placeholder="$t('message.all')">
                <el-option v-for="item in options.profession"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
		         </el-select>
		    </el-form-item>
     </el-col>
  	</el-row>
    <el-row  :gutter="24"   style="height: 50px;">
            <el-col :span="12">
            	    <el-form-item :label="$t('culture.exceptionSetting.exception')" prop="type">
		                 <el-select style="width: 100%;" v-model="model.type" :placeholder="$t('message.all')">
		                   <el-option v-for="item in options.type"
		                     :key="item.value"
		                     :label="item.label"
		                     :value="item.value">
		                   </el-option>
		                 </el-select>
		                </el-form-item>
            	</el-col>
            </el-row>
      </el-form>
     <span slot="footer">
        <el-button  @click="cancel">{{$t('message.cancel')}}</el-button>
        <el-button type="primary"   @click="confirm">{{ $t('message.confirm') }}</el-button>
      </span>
    </el-dialog>
    </div>
</template>
<script>
import bus from 'common/src/utils/bus';
import UTILS from 'common/src/utils/utils'
import { queryDic, findTrainingLevelByProjId } from 'common/src/api/dictionary'
import { findFaculty } from "common/src/api/faculty";
import { 
         findExceptions,
         addException,
         editException,
         delException
        } from "common/src/api/culture/exceptionSetting"
import { findProByParam } from "common/src/api/culture/campusProfession"
import { getGraduateDegreePage } from "common/src/api/resource/course";
export default {
  name: "exceptionSetting",
  data() {
    return {
      tableData: [],
      options: {
        type:[],
        faculty: [],
        trainingLevel:[],
        profession: [],
      },
      isEdit: false,
      showDialog: false,
      dialogTitle: "",
      queryForm: {
         pageNum_: 1,
         pageSize_: 20,
         total_:0,
         grade: '',      
         trainingLevel:"",
         faculty:"",
         profession: '',
         type:"",
         projId: ""
      },
      model: {
         id:"",
         grade: "",
         trainingLevel:"",
         faculty:"",
         profession:"",
         professionName:"",
         type:""
      },
      rules: {
         grade: [
          {
            required: true,
            message: this.$t('culture.rules.plsChooseGrade'), 
            trigger: "blur"
          }
        ],
         trainingLevel: [
          {
            required: true,
            message: this.$t('culture.rules.plsChooseTrainingLevel'), 
            trigger: "blur"
          }
        ],
        faculty: [
          {
            required: true,
            message: this.$t('culture.rules.plsChooseFaculy'),
            trigger: "blur"
          }
        ],
        profession: [
          {
            required: true,
            message: this.$t('culture.rules.plsChooseProfession'),
            trigger: "blur"
          }
        ],
        type: [
          {
            required: true,
            message: this.$t('culture.rules.plsChooseException'),
            trigger: "blur"
          }
        ],
      }
    };
  },
  created() {
    this.$store.getters.getFuncUnderPage(this.$route.path).then(funcs => {
      this.functions = funcs;
    });
  },
  mounted() {
    bus.$on('updateCurrentManageDeptId', (currentManageDeptId) => {
        this.queryForm.projId = currentManageDeptId;
        this.initTrainingLevelOptions();
    })
    this.initProjId();
    this.initOptions();
    this.initTrainingLevelOptions();
  },

  methods: {
    initProjId(){
      let currentUser = (this.$store.state.session && this.$store.state.session.user) || JSON.parse(localStorage.getItem('user')); 
      this.queryForm.projId = currentUser.currentManageDptId;
    },
    initTrainingLevelOptions(){
      findTrainingLevelByProjId(this.queryForm.projId).then(res => {
			    if (res.code === 200) {
			        this.queryForm.trainingLevel = "";
			        this.loadTrainingLevelOptions("trainingLevel", res.data);
			    }
			});
    },
    loadTrainingLevelOptions(optionKey, dataObj) {
        this.options[optionKey] = [];
        _.each(dataObj, level => {
            this.options[optionKey].push({
                label:
                    "en" === this.$store.getters.language
                        ? level.nameEN
                        : level.nameCN,
                value: level.code
            });
        });
    },
    getProfessions() {
       let postData=_.cloneDeep(this.queryForm);
        postData.grade=Number(postData.grade);
      findExceptions(postData).then(res => {
        if(res.code==200){
          this.tableData=res.data.list;
          this.queryForm.pageNum_=res.data.pageNum_;
          this.queryForm.pageSize_=res.data.pageSize_;
          this.queryForm.total_ = res.data.total_;
        }
      });
    },
     initOptions() {
      if (this.queryForm.projId == 1) {
          this.options.type.push({
            label: this.$t('culture.exceptionSetting.CourseException'),
            value: '1'
          });
      } else {
        this.options.type.push({
          label: this.$t('culture.exceptionSetting.exportException'),
          value: "2"
        });
      }
      // this.options.type.push({
      //   label: this.$t('culture.exceptionSetting.CourseException'),
      //   value: '1'
      // });
      // this.options.type.push({
      //   label: this.$t('culture.exceptionSetting.exportException'),
      //   value: "2"
      // });
      findFaculty().then(res => { 
          let data = {"X_YX": res.data};
          UTILS.fillSelect({ faculty: "X_YX" }, data, this.options);
      });
      this.getProfessions();
    },
   getProfession(val) {
     this.queryForm.profession='';
     this.options.profession=[];
     if(this.queryForm.projId==='1'){
       // 联动校验
       if(!(this.queryForm.grade && this.queryForm.faculty)) {
         return
       }
     }
     this.queryMajors(true,val);  
   },
   getProfessionEdit(val) {     
     this.model.profession='';
     this.options.profession=[];
     if(this.queryForm.projId==='1'){
       // 联动校验
       if(!(this.model.grade && this.model.faculty)) {
         // 年级选择提示
         this.$refs.model.validateField('grade');
         return
       }
     }
     this.queryMajors(false,val);
   },
   //本科生和研究生对应的校内专业和专业,第一个参数是区分搜索和新增
   queryMajors(searchFlag,val){
     //区分本科和研究生专业
        if(this.queryForm.projId==='1'){
          let postData;
          if(searchFlag){
              postData=_.cloneDeep(this.queryForm);
              postData.grade=Number(postData.grade);
              delete postData.trainingLevel; 
          }else{
              postData=_.cloneDeep(this.model);
              postData.grade=Number(postData.grade);
              delete postData.trainingLevel;
          }
          findProByParam(postData).then(res => {
            if(res.code==200){
              this.options.profession= res.data.map(i => ({
                  value: i.professionCateGory,
                  label: i.professionCateGoryName
              }))
            }
          })
        }else {
            if (val) {
                this.options["profession"] = [];
                const data = {
                    college: val,
                    page: false
                };
                getGraduateDegreePage(data).then(res => {
                    if (res.code === 200) {
                        this.options["profession"] = [];
                        let majors = _.map(res.data.list, item => {
                            return {
                                value: item.code,
                                label:
                                    "cn" !== this.$store.getters.language
                                        ? item.nameEn
                                        : item.name
                            };
                        });
                        majors && 0 < majors.length &&
                      (this.options["profession"] = [
                          ...this.options["profession"],
                          ...majors
                      ]);
                    }
                });
            }
        } 
   },
   onPageSizeChange(size) {
      this.queryForm.pageSize_ = size;
      this.getProfessions();
    },
    onCurrentPageChange(currentPage) {
      this.queryForm.pageNum_ = currentPage;
      this.getProfessions();
    },
   getTypeStr(val) {
     if(!val){
       return "";
     }else{
      let str='';
       this.options.type.forEach(element => {
         if(element.value===val){
           str=element.label;
         }
       });
       return str;
     }
   },
   resetFormValidate() {
      this.getProfession();
      this.$refs.model.resetFields();
    },
    reset() {
      this.queryForm.grade = "";
      this.queryForm.faculty = "";
      this.queryForm.trainingLevel ="";
      this.queryForm.profession="";
      this.queryForm.type ="";
      this.getProfessions();
    },
    resetAdd() {
      this.model.grade='';
      this.model.trainingLevel='';
      this.model.faculty='';
      this.model.profession='';
    },
    addExcept() {      
      this.resetAdd();
      this.isEdit=false;
      this.dialogTitle=this.getdialogTitle(this.isEdit);
      this.model.type=this.queryForm.type;
      this.showDialog=true;
    },
    editExcept(data) {
      this.showDialog=true;
      this.isEdit=true;
      this.dialogTitle=this.getdialogTitle(this.isEdit);
      this.model.id=data.id;
      this.model.grade=data.grade+"";
      this.model.trainingLevel=data.trainingLevel;
      this.model.faculty=data.faculty;
      this.model.profession=data.profession;
      this.model.type=data.type;
      this.queryMajors(false,this.model.faculty);
    },
    getdialogTitle(val) {
      return val
        ? this.$t('message.edit')
        : this.$t('message.add');
    },
     confirm() {
       this.$refs.model.validate(valid => {
         if (!valid) {
           return;
        }
        let postData=_.cloneDeep(this.model);
        postData.grade=Number(postData.grade);
        for (const item of this.options.profession) {
            if(postData.profession===item.value){
                 postData.professionName = item.label;
            }
        }
        
        if(this.isEdit){
             editException(postData).then(res => {
          if(res.code==200){
             this.$message({
                type: "success",
                message: this.$t("message.editSuccess")
              });
              this.showDialog=false;
              this.reset();
          }
        });
        }else{
          addException(postData).then(res => {
            if(res.code==200){
               this.$message({
                  type: "success",
                  message: this.$t("message.addSuccess")
                });
                this.showDialog=false;
                this.reset();
            }
          });
         }
        });
    },
    cancel() {
      this.showDialog=false;
      this.getProfession();
    },
    delExcept(id) {
       this.$confirm(
         this.$t("message.deleteConfirm"),
        this.$t("message.prompt"),
        {
          confirmButtonText: this.$t("message.confirm"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }
      ).then(_ => {
        delException(id).then(res => {
          if(res.code==200){
            this.$message({
                type: "success",
                message: this.$t("message.deleteSuccess")
              });
              this.getProfessions();
          }
        });
      });
    },
  }
};
</script>

